﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WaterRevenueMS.WebUI.Common;
using System.ComponentModel.Composition;
using WaterRevenueMS.WebUI.Extension.Filters;
using WaterRevenueMS.Domain.Common.Models;
using WaterRevenueMS.Domain.ViewModels.BaseData;
using WaterRevenueMS.Componnent.Entities.BaseData;
using System.Linq.Expressions;
using WaterRevenueMS.WebUI.Extension.MvcHelper;
using WaterRevenueMS.Componnent.Common;
using WaterRevenueMS.Core.Service.BasicSet;
using WaterRevenueMS.Core.Service.BasicSet.Impl;
using WaterRevenueMS.Core.Service.BaseData;
using WaterRevenueMS.Core.Repository.BaseData;
using WaterRevenueMS.Domain.ViewModels.BaseData.Area;
using WaterRevenueMS.Domain.ViewModels.BaseData.MeterBook;
using System.Web.UI;

namespace WaterRevenueMS.WebUI.Controllers
{
    [Export]
    [PartCreationPolicy(CreationPolicy.NonShared)]
    public class MeterBookController : AdminController
    {
        [Import]
        public IAreaService AreaService { get; set; }
        [Import]
        public IMeterBookService MeterBookService { get; set; }

         [AdminLayoutAttribute]
        public ActionResult Index()
        {
            var model = new MeterBookModel();
            #region 区域
            var parentModuleData = AreaService.Areas.Where(t => t.IsDeleted == false)
            .Select(t => new MeterBookModel
            {
                AreaId = t.Id,
                AreaName = t.Qu_YMC
            });
            foreach (var item in parentModuleData)
            {
                model.Search.AreaItems.Add(new SelectListItem { Text = item.AreaName, Value = item.AreaId.ToString() });
            }
            #endregion
            return View(model);
        }

        [AdminPermission(PermissionCustomMode.Ignore)]
        public ActionResult List(DataTableParameter param)
        {
            int total = MeterBookService.MeterBooks.Count(t => t.IsDeleted == false);

            var expr = BuildSearchCriteria();

            var filterResult = MeterBookService.MeterBooks.Where(expr).Select(t => new MeterBookModel
            {
                id = t.Id,
                Biao_CMC = t.Biao_CMC,
                AreaName = t.Area != null ? t.Area.Qu_YMC : "",
                OrderNo = t.OrderNo ,
                AreaId = t.Qu_YSZ_No,
                
                Biao_CBH = t.Biao_CBH

            }).OrderBy(t => t.id).Skip(param.iDisplayStart).Take(param.iDisplayLength).ToList();

            int sortId = param.iDisplayStart + 1;

            var result = from c in filterResult
                         select new[]
                        {
                            sortId++.ToString(), 
                            c.Biao_CMC,
                            c.Biao_CBH,
                            c.AreaName,
                            c.AreaId.ToString(),
                            c.OrderNo.ToString(),
                            c.id.ToString()
                        };

            return Json(new
            {
                sEcho = param.sEcho,
                iDisplayStart = param.iDisplayStart,
                iTotalRecords = total,
                iTotalDisplayRecords = total,
                aaData = result
            }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult Create()
        {
            var model = new MeterBookModel();
            InitMeterBookModel(model);
            return PartialView(model);
        }

        [HttpPost]
        [AdminOperateLog]
        public ActionResult Create(MeterBookModel model)
        {
            InitMeterBookModel(model);
            if (ModelState.IsValid)
            {
                OperationResult result = MeterBookService.Insert(model);
                if (result.ResultType == OperationResultType.Success)
                {
                    return Json(result);
                }
                else
                {
                    return PartialView(model);
                }
            }
            else
            {
                return PartialView(model);
            }
        }

        public ActionResult Edit(int Id)
        {
            var model = new MeterBookModel();
            
            var entity = MeterBookService.MeterBooks.FirstOrDefault(t => t.Id == Id);
            if (null != entity)
            {
                model = new MeterBookModel
                {
                    id = entity.Id,
                    Biao_CMC= entity.Biao_CMC,
                    Biao_CBH = entity.Biao_CBH,
                  //  AreaName = entity.Area.Qu_YMC,
                    AreaId = entity.Qu_YSZ_No,
                    OrderNo = entity.OrderNo


                };
            }
            InitMeterBookModel(model);
            return PartialView(model);
        }

        [HttpPost]
        public ActionResult Edit(MeterBookModel model)
        {
          //  InitMeterBookModel(model);
            if (ModelState.IsValid)
            {
                OperationResult result = MeterBookService.Update(model);
                if (result.ResultType == OperationResultType.Success)
                {
                    return Json(result);
                }
                else
                {
                    return PartialView(model);
                }

            }
            else
            {
                return PartialView(model);
            }
        }


        public ActionResult Delete(int Id)
        {
            OperationResult result = MeterBookService.Delete(Id);
            return Json(result);
        }

        [AdminPermission(PermissionCustomMode.Ignore)]
        [OutputCache(Location = OutputCacheLocation.None, NoStore = true)]
        public JsonResult IsUnique_Available(string Biao_CBH)
        {
            if (!string.IsNullOrEmpty(Biao_CBH))
            {
                var entity = MeterBookService.MeterBooks.FirstOrDefault(t => t.Biao_CBH == Biao_CBH);
                if (entity != null)
                {
                    //string message = "该用户编号已经存在";
                    return Json(false, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    return Json(true, JsonRequestBehavior.AllowGet);
                }
            }
            return Json(true, JsonRequestBehavior.AllowGet);
        }


        private Expression<Func<MeterBook, Boolean>> BuildSearchCriteria()
        {
            DynamicLambda<MeterBook> bulider = new DynamicLambda<MeterBook>();
            Expression<Func<MeterBook, Boolean>> expr = null;
            if (!string.IsNullOrEmpty(Request["Biao_CMC"]))
            {
                var data = Request["Biao_CMC"].Trim();
                Expression<Func<MeterBook, Boolean>> tmp = t => t.Biao_CMC.Contains(data);
                expr = bulider.BuildQueryAnd(expr, tmp);
            }
            if (!string.IsNullOrEmpty(Request["Biao_CBH"]) && Request["Biao_CBH"] != "0")
            {
                var data = Request["Biao_CBH"].Trim();
                Expression<Func<MeterBook, Boolean>> tmp = t => t.Biao_CBH.ToString().Contains(data);
                expr = bulider.BuildQueryAnd(expr, tmp);
            }
            if (!string.IsNullOrEmpty(Request["Qu_YSZ_No"]) && Request["Qu_YSZ_No"] != "0")
            {
                var data = Convert.ToInt32(Request["Qu_YSZ_No"]);
                Expression<Func<MeterBook, Boolean>> tmp = t => (t.Id == data) || (t.Qu_YSZ_No == data);
                expr = bulider.BuildQueryAnd(expr, tmp);
            }


            Expression<Func<MeterBook, Boolean>> tmpSolid = t => t.IsDeleted == false;
            expr = bulider.BuildQueryAnd(expr, tmpSolid);

            return expr;
        }

        private void InitMeterBookModel(MeterBookModel model)
        {
            #region 区域
            var parentModuleData = AreaService.Areas.Where(t => t.IsDeleted == false)
            .Select(t => new MeterBookModel
            {
                AreaId = t.Id,
                AreaName = t.Qu_YMC
            });
            foreach (var item in parentModuleData)
            {
                model.AreaItems.Add(new SelectListItem { Text = item.AreaName, Value = item.AreaId.ToString() });
            }
            #endregion
        }

    }
}
